/**
 *
 * Copyright by Samuel Castro & Joaquim Fonseca, 2011
 * All Rights Reserved
 *
 * NOTES:
 * Please do not redistribute this plugin without my permission
 * Plugin made for private use only
 *
 */
package com.SySammy.sdMiningChallenge.Listeners;

import com.SySammy.sdMiningChallenge.challengeMethods;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityListener;

public class sdPlayerListener extends EntityListener {

    private challengeMethods CM = new challengeMethods();

    @Override
    public void onEntityDeath(EntityDeathEvent event) {
        if (event instanceof EntityDeathEvent && challengeMethods.started == true) {
            EntityDeathEvent sub = (EntityDeathEvent) event;
            if ((sub.getEntity() instanceof Player)) {
                Player killed = (Player) sub.getEntity();
                challengeMethods.scores.remove(killed.getName());
                if (challengeMethods.scores.size() < 1) {
                    CM.StopChallenge();
                }
                if (killed != null) {
                    killed.sendMessage(ChatColor.RED + "[MC]: Sorry, by dying you lost the challenge");
                    killed.getServer().broadcastMessage(ChatColor.DARK_PURPLE + "[MC]: " + killed.getName() + " is off the challenge");
                    killed.getServer().broadcastMessage(ChatColor.DARK_PURPLE + "[MC]: Everyone's dead, no one wins.");
                }
            }
        }
    }

    @Override
    public void onEntityDamage(EntityDamageEvent event) {
        if (event instanceof EntityDamageByEntityEvent && challengeMethods.started == true) {
            EntityDamageByEntityEvent sub = (EntityDamageByEntityEvent) event;
            if ((sub.getDamager() instanceof Player) && (sub.getEntity() instanceof Player)) {
                Player attacker = (Player) sub.getDamager();
                if (attacker != null) {
                    if (challengeMethods.scores.containsKey(attacker.getName())) {
                        attacker.sendMessage(ChatColor.RED + "[MC]: PVP is disabled while the challenge is running.");
                        event.setCancelled(true);
                    }
                }

            }
        }
    }
}
